<?php
class image_library {
    function move_file($from, $to)
	{
		$upload_mode = (@ini_get('open_basedir') || @ini_get('safe_mode') || strtolower(@ini_get('safe_mode')) == 'on') ? 'move' : 'copy';
		switch ($upload_mode)
		{
			case 'copy':
				if (!@copy($from, $to))
				{
					if (!@move_uploaded_file($from, $to))
					{
						return false;
					}
				}
				@unlink($from);
				break;
			
			case 'move':
				if (!@move_uploaded_file($from, $to))
				{
					if (!@copy($from, $to))
					{
						return false;
					}
				}
				@unlink($from);
				break;
		}
		@chmod($to, 0666);
		return true;
	}
	function resizeThumbnailImage($image_thumb, $image, $width, $height, $start_width, $start_height, $scale=0)
	{
		list($imagewidth, $imageheight, $imageType) = getimagesize($image);
		$imageType = image_type_to_mime_type($imageType);
		
		if (!$imagewidth || !$imageheight) {
			return;
		}
		
		$xpos = 0;
		$ypos = 0;
	
		$scale = min($width /$imagewidth , $height / $imageheight);
		
		if ($scale == 1 || ($width >$imagewidth && $height>$imageheight )) {
			//lay file goc bo qua
			copy($image,$image_thumb);
		}
		else 
		{
			$new_width = (int)($imagewidth * $scale);
			$new_height = (int)($imageheight * $scale);			
			
			//$xpos = (int)(($width - $new_width) / 2);
			//$ypos = (int)(($height - $new_height) / 2);
		
			$newImage = imagecreatetruecolor($new_width, $new_height);
			$background = imagecolorallocate($newImage, 255, 255, 255);
	    	imagefilledrectangle($newImage, 0, 0, $width, $height, $background);
			switch ($imageType)
			{
				case 'image/gif':
					$source = imagecreatefromgif ($image);
					break;
				case 'image/pjpeg':
				case 'image/jpeg':
				case 'image/jpg':
					$source = imagecreatefromjpeg($image);
					break;
				case 'image/png':
				case 'image/x-png':
					$source = imagecreatefrompng($image);
					break;
			}	
			
		
		
		    imagecopyresampled($newImage, $source, 0, 0, 0, 0, $new_width, $new_height, $imagewidth, $imageheight);
		    imagedestroy($source);
		    
		    switch ($imageType)
			{
				case 'image/gif':
					imagegif ($newImage, $image_thumb);
					break;
				case 'image/pjpeg':
				case 'image/jpeg':
				case 'image/jpg':
					imagejpeg($newImage, $image_thumb, 90);
					break;
				case 'image/png':
				case 'image/x-png':
					imagepng($newImage, $image_thumb);
					break;
			}
			chmod($image_thumb, 0777);
		}	
		return $image_thumb;
	}
}
?>